<?php

class ImageTable extends Doctrine_Table
{

  public function getPager($albumId=0, $keyword=0, $page=1)
  {
      $q = Doctrine_Query::create()
           ->select('i.*')
           ->where('i.id is not null')
           ->from('Image i');
           
           if($albumId) $q->andWhere('i.album_id = ?', $albumId);
           
           if($keyword) $q->andWhere('i.description like ? OR i.filename like ?', array('%'.$title.'%', '%'.$title.'%'));

           $q->orderBy('i.created_at ASC');
           
      $pager = new sfDoctrinePager('Image', 30);
      $pager->setPage($page);
      $pager->setQuery($q);
      $pager->init();
      
      return $pager;
  }




  public function fetchall($params = array())
  {
      $q = Doctrine_Query::create()
              ->select('*')
              ->from('Image');

              // TYPE
              if(isset($params['albumId']) && $params['albumId']) 
                $q->where('album_id = ?', $params['albumId']);
                
              // KEYWORD
              if(isset($params['keyword']) && $params['keyword'])
                $q->andWhere('description LIKE ? OR filename LIKE ?', array('%'.$params['keyword'].'%', '%'.$params['keyword'].'%'));
                
              // SORT
              $q->orderBy('created_at DESC');

              // LIMIT
              $limit = isset($params['limit']) ? $params['limit'] : 30;
              $q->limit($limit);
  
      return $q->execute();
  }
  

  
  
  
  
  
  
  
  
  
  
  
  
  public function findByObject($objectType, $objectId)
  {
    $q = Doctrine_Query::create()
            ->from('Image')
            ->where('object_type = ? AND object_id = ? ', array($objectType, $objectId))
            ->orderBy('created_at DESC, title ASC');
    return $q->execute();
  }
  
  public function deleteByObject($objectType, $objectId)
  {
    $q = Doctrine_Query::create()
            ->from('Image')
            ->where('object_type = ? AND object_id = ? ', array($objectType, $objectId));
    $rss = $q->execute();

    foreach ($rss as $rs)
    {
      try {
        @unlink(sfConfig::get('sf_upload_dir').'/'.$objectType.'/'.$rs->getPath().'/'.$rs->getFilename());
        @unlink(sfConfig::get('sf_upload_dir').'/'.$objectType.'/'.$rs->getPath().'/80-'.$rs->getFilename());
        $rs->delete();
      }catch (Exception $e){}
    }

  }
    
  public function getImage($objectType, $objectId)
  {
    $q = Doctrine_Query::create()
            ->from('Image')
            ->where('object_type = ? AND object_id = ? ', array($objectType, $objectId));
    $results = $q->fetchOne();
  }
    
}